/*
 * @Author: 
 * @Date: 2024-05-29 10:19:41
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-03-31 09:44:55
 * @Description: 
 */
import { Body, Inject, Controller, Get, Post, Query } from '@midwayjs/core';
import { addGraphDto } from '../dto/ForderDto'
import { FolderResponse } from '../interface'
import * as fs from 'fs';
import * as path from 'path';

@Controller('/folder')
export class FolderController {

    @Post('/getLazyFolderContent')
    async getLazyFolderContent(@Body() requestBody: addGraphDto) {
        const { folderPath } = requestBody;
        console.log(folderPath)
        const folders = await this.listFolders(folderPath);
        const treeData: FolderResponse[] = folders.map(folder => {
            return { name: folder.name, leaf: folder.leaf, fullPath: folder.fullPath };
        });
        return treeData;
    }

    async listFolders(folderPath: string): Promise<{ name: string, leaf: boolean, fullPath: string }[]> {
        const files = await fs.promises.readdir(folderPath);
        const folders = [];
        for (const file of files) {
            const filePath = path.join(folderPath, file);
            const stats = await fs.promises.stat(filePath);
            if (stats.isDirectory()) {
                // 如果是文件夹，则记录文件夹名称，并判断是否有子文件夹
                const subFiles = await fs.promises.readdir(filePath);
                const hasChildren = subFiles.some(subFile => {
                    return fs.statSync(path.join(filePath, subFile)).isDirectory();
                });
                folders.push({ name: file, leaf: !hasChildren, fullPath: filePath });
            }
        }
        return folders;
    }

    @Post('/fileList')
    async getFileList(@Body() requestBody: addGraphDto) {
        try {
            const { folderPath, type } = requestBody;

            // 检查文件夹路径是否存在
            if (!fs.existsSync(folderPath)) {
                return { message: '文件夹不存在' };
            }

            // 读取文件夹中的文件列表
            const files = await fs.promises.readdir(folderPath);
            const fileList: any[] = [];

            for (const file of files) {
                const filePath = path.join(folderPath, file).replace(/\\/g, '/');
                const stats = await fs.promises.stat(filePath);
                // 如果文件不是文件夹，并且文件扩展名在指定类型中，则将其添加到文件列表中
                if (!stats.isDirectory()) {
                    const fileInfo = {
                        name: file, // 文件名
                        date: stats.mtime.toISOString(), // 最后修改日期
                        type: path.extname(file), // 文件类型（后缀）
                        size: stats.size, // 文件大小（字节）
                        fullPath: filePath // 文件完整路径
                    };
                    if (type.length > 0) {
                        type.indexOf(path.extname(file)) !== -1 && fileList.push(fileInfo);
                    } else {
                        fileList.push(fileInfo);
                    }
                }

            }
            // 返回文件列表
            return { files: fileList };
        } catch (error) {
            console.error('错误:', error);
            throw new Error('内部服务器错误');
        }
    }
}
